package org.vacoor.nothing.security.solr.filter;

import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.servlet.SolrDispatchFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

/**
 * <pre>
 * solr.home
 *    | -- solr.xml
 *    | -- instance
 *           | -- conf
 *                  | -- solrconfig.xml         solr 实例配置, 查询, 补全等
 *                  | -- schema.xml             document 字段配置
 *                  | -- dataimport.properties  自动生成, 记录最后导入时间
 *           | -- data
 *                 | -- index      索引文件
 *                 | -- tlog       日志文件
 *           | -- core.properties  内容为 name = core name
 * </pre>
 */

/**
 * 主要实现功能就一个, 获取 solr core container 创建一个 EmbeddedSolrServer
 */
public class CustomSolrDispatchFilter extends SolrDispatchFilter {
    private static final Logger LOG = LoggerFactory.getLogger(CustomSolrDispatchFilter.class);

    public static final String EMBEDDED_SOLR_SERVER_KEY = CustomSolrDispatchFilter.class + ".embeddedSolrServer";

    private FilterConfig config;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;

        LOG.info("CustomSolrDispatchFilter.init()");
        /**
         *  path-prefix
         *  config.getInitParameter("path-prefix");
         *  <p />
         *  solr home
         *  1. JNDI: java:comp/env/solr/home
         *  2. System Property: solr.solr.home
         *  3. solr/ (user.dir/solr)
         *  首先从 JNDI 因此可以在 web.xml
         *  &lt;env-entry&gt;
         *     &lt;env-entry-name&gt;solr/home&lt;/env-entry-name&gt;
         *     &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
         *     &lt;env-entry-value&gt;/usr/app/solr/home&lt;/env-entry-value&gt;
         *  &lt;/env-entry&gt;
         */
        super.init(config);

        EmbeddedSolrServer embeddedSolrServer = new EmbeddedSolrServer(cores, cores.getDefaultCoreName());
        ServletContext ctx = config.getServletContext();
        ctx.setAttribute(EMBEDDED_SOLR_SERVER_KEY, embeddedSolrServer);
    }

    @Override
    public void destroy() {
        ServletContext ctx = config.getServletContext();
        EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) ctx.getAttribute(EMBEDDED_SOLR_SERVER_KEY);

        ctx.removeAttribute(EMBEDDED_SOLR_SERVER_KEY);
        if (null != embeddedSolrServer) {
            // embeddedSolrServer.shutdown();   // 会调用 coreContainer.shutdown(); super.destroy() 已经调用
        }

        super.destroy();
        this.config = null;
    }
}
